<template>
  <div style="min-height: 100px;position: relative">
    <sticky-header :style="{height: '40px'}" :top="530" v-if="sticky&&currentSpuList.length">
      <div class="collection_batch_tip sticky-header" :style="{color: dragLockArea ? '#3399ff' : 'rgba(0, 0, 0, 0.65)'}"
           style="min-height: 40px">
        {{ dragLockArea ? '置顶商品只能在蓝色区域内移动' : '请通过点击商品或框选出你需要的商品，拖拽或点击“批量移动”，移动到你理想中的位置' }}
        <el-button size="mini" @click="handleSelectAll" v-if="showSelectAll" style="margin-left: 10px">全选</el-button>
        <el-button size="mini" @click="handleCancelSelectAll" v-if="selectNum > 0 && showSelectAll">取消选择
          <el-tooltip class="item" effect="dark" content="取消所有页面选中添加的商品" placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>
        </el-button>
        <el-dropdown size="mini" type="default" style="margin-left: 10px;margin-right: 10px"
                     v-if="selectNum > 0 && showSelectAll"
                     @command="handleCommand">
          <el-button class="el-dropdown-link" size="mini">
            批量操作<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="moveTop">移动至首页顶部</el-dropdown-item>
            <el-dropdown-item command="moveCurrentTop">移动至当前页首部</el-dropdown-item>
            <el-dropdown-item command="moveBottom">移动至末页底部</el-dropdown-item>
            <el-dropdown-item command="movePrevTop" :disabled="page < 2">移动至上一页顶部</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="select_num" v-if="selectNum > 0&&showSelectAll">
          已选<span>{{ selectNum }}</span>个商品
        </div>
      </div>
    </sticky-header>
    <div class="list-wrap">
      <div class="batch-product_item" v-if="dragLockArea">
<!--        <div v-for="(item, index) in lockList.slice(0, cacheLen + 1)" :key="index" class="mark-item"-->
<!--             :class="{'hasRightBorder': item.last,  'isFirst': item.first, 'isLast': (index + 1) >   everyRowItems * (rowItems - 1),'hasTopBorder': everyRowItems > index, 'hasBottomBorder' : (index < (everyRowItems * rowItems) && everyRowItems * (rowItems - 1) < index+1) || (index + 1) > ttttt,  'hasBottomBorder hasRightBorder':rowItems > 2 && (index+1) > (everyRowItems * (rowItems - 1))}">-->
        <div v-for="(item, index) in lockList.slice(0, cacheLen + 1)" :key="index" class="mark-item">
        </div>
      </div>
      <draggable
          ref="draglist"
          class="drag"
          :multi-drag="multiDrag"
          selected-class="seleted-pic"
          filter=".forbid"
          v-model="currentSpuList"
          @change="log($event, 'change')"
          @select="log($event, 'add')"
          @deselect="log($event, 'des')"
          :move="move"
          @end="dragend"
          @filter="handleFilter"
          @start="choose"
          :options="{
          delay: 300,
          touchStartThreshold: 2000,
          animation: 120,
          ghostClass: 'sortable-ghost',
          chosenClass: 'chosenClass',
          scroll: true,
          scrollSensitivity: 200,
          forceFallback: true

                  }"
      >
        <div
            class="image-item"
            :data-key="$item.spuId"
            v-for="($item, $index) in currentSpuList"
            :key="$index"
            :class="(noDrag || $item.canDrag)  ?'forbid':'sort-item'"
        >
          <div v-if="$item.showCount && count > 1"
               style="width: 20px;height: 20px;border-radius: 50%;background: red;position: absolute;right: 0;top:-10px;color: #fff;text-align: center">
            {{ count }}
          </div>
          <div class="img">
            <img v-lazy="fillImg($item.spuImage)" alt="" class="l-img"/>
            <div class="label" v-if="selectNum < 2">
              <el-tooltip class="item" effect="dark" content="置顶" placement="top" v-if="!$item.top">
                <div @click.stop="actionTop($index, $item, $event)">
                  <svg-icon icon-class="top"></svg-icon>
                </div>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="取消置顶" placement="top" v-if="$item.top">
                <div @click.stop="actionCancelTop($index, $item)">
                  <svg-icon icon-class="top" style="opacity: 0.4"></svg-icon>
                </div>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top" style="margin-left: 20px">
                <div>
                  <router-link target="_blank"
                               :to="{name: 'goods-detail', params:{id: $item.spuId}, query: $route.query}">
                    <svg-icon icon-class="edit"></svg-icon>
                  </router-link>
                </div>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top" style="margin-left: 20px"
                          v-if="!$item.top && seriesTypes === 'manual'">
                <div @click="actionDelTop($item)">
                  <svg-icon icon-class="remove"></svg-icon>
                </div>
              </el-tooltip>
            </div>
            <div class="right_top_flag" v-if="$item.top">
              <div class="top_flag_wrapper">
                <img
                    src="">
              </div>
            </div>
          </div>
          <div class="title">{{ $item.spuName }}</div>
          <div class="collection-product_bottom">
          <span
              :class="['tag', $item.published === 1 ? 'tag-green': '']">{{
              $item.published === 1 ? '已上架' : '未上架'
            }}</span>
            <span class="top" v-if="$item.top">已置顶</span>
          </div>
        </div>
      </draggable>
      <empty style="justify-content: center" v-if="imageList.length === 0"/>
      <el-pagination
          v-if="currentSpuList.length"
          class="pagination"
          background
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="page"
          :page-sizes="[50, 100, 200, 400, 600]"
          :page-size="50"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import bgPic from '@/assets/images/bg-grey.png';
import draggable from '_c/multiDrag';
import stickyHeader from '_c/StickyHeader';
import {debounce, deepClone} from '@/utils/utils';
import equal from 'fast-deep-equal';

export default {
    components: {draggable, stickyHeader},
    props: {
        sticky: {
            type: Boolean,
            default: false
        },
        noDrag: {
            type: Boolean,
            default: false
        },
        value: {
            type: Array,
            default: () => []
        },
        seriesType: {
            type: String,
            default: 'automatic'
        }
    },
    watch: {
        value: {
            handler (value) {
                this.count = 0;
                this.selectNum = 0;
                this.selectItems = [];
                this.handleCancelSelectAll();
                this.imageList = value;
                this.initialCurrentPageSpu();
            },
            immediate: true
        }
    },
    computed: {
        seriesTypes () {
            return this.seriesType;
        }
    },
    data () {
        return {
            multiDrag: true,
            bgPic,
            showSelectAll: true,
            dragLockArea: false,
            imageList: this.value,
            currentSpuList: [],
            page: 1,
            total: 0,
            pageSize: 50,
            pageCount: 0,
            count: 0,
            lockItemLen: 0,
            lockList: [],
            everyRowItems: 0,
            rowItems: 0,
            ttttt: 0,
            cacheLen: 0,
            selectNum: 0,
            selectItems: [] // 选择的商品
        };
    },
    destroyed () {
        window.removeEventListener('resize', this.__resizeHandler);
    },
    mounted () {
    },
    methods: {
        handleCommand (command) {
            const lockItems = this.imageList.filter(res => res.top);
            const currentLockItem = this.currentSpuList.filter(res => res.top);
            this.selectItems.forEach(val => {
                const index = this.imageList.findIndex(res => res.spuId === val.spuId);
                this.imageList.splice(index, 1);
            });
            if (command === 'moveTop') {
                this.imageList.splice(lockItems.length, 0, ...this.selectItems);
            } else if (command === 'moveCurrentTop') {
                this.imageList.splice(currentLockItem.length + this.pageSize * (this.page - 1), 0, ...this.selectItems);
            } else if (command === 'moveBottom') {
                this.imageList.push(...this.selectItems);
            } else if (command === 'movePrevTop') {
                this.imageList.splice(lockItems.length + this.pageSize * (this.page - 2), 0, ...this.selectItems);
            }

            this.handleCancelSelectAll();
            this.$emit('input', this.imageList);
            this.$emit('update', {type: 'drag'});
        },
        // 全选全部(置顶除外）
        handleSelectAll () {
            this.selectItems = this.currentSpuList.filter(res => !res.top);
            const items = document.querySelectorAll('.sort-item');
            this.selectNum = items.length;
            this.$refs.draglist.selectAll(items);
        },
        // 取消全选
        handleCancelSelectAll () {
            this.count = 0;
            this.selectItems = [];
            this.selectNum = 0;
            this.$nextTick(() => {
                if (document.querySelectorAll('.image-item').length) {
                    this.$refs.draglist.deSelectAll(document.querySelectorAll('.image-item'));
                }
            });
        },
        log (evt, name) {
            if (name === 'add' || name === 'des') {
                let indexs = evt.newIndicies.map(s => s.index);
                // 如果选择的是不置顶商品 那么屏蔽所有可置顶商品，使之不能拖拽
                if (indexs.some(s => (s + 1) > this.lockItemLen)) {
                    this.showSelectAll = true;
                    this.dragLockArea = false;
                    this.currentSpuList.forEach(res => {
                        this.$set(res, 'canDrag', res.top);
                    });
                } else if (indexs.length) {
                    // this.lockArea();
                    this.dragLockArea = true;
                }
                this.selectItems = [];
                indexs.sort((a, b) => a - b).forEach(ss => {
                    if (this.currentSpuList[ss] && !this.currentSpuList[ss].top) {
                        this.selectItems.push(this.currentSpuList[ss]);
                    }
                });
            }
            if (name === 'add') {
                this.count++;
                this.selectNum++;
            }
            if (name === 'des') {
                this.count--;
                this.selectNum--;
            }
            if (name === 'change') {
                this.selectNum = 0;
                this.count = 0;
            }
        },
        handleFilter (evt) {
            this.handleCancelSelectAll();
            this.showSelectAll = false;
            // 锁定的商品恢复成拖拽模式, 限制拖拽条件
            // 如果被锁的是不置顶商品
            if ((evt.oldIndex + 1) > this.lockItemLen) {
                this.multiDrag = true;
                this.currentSpuList.forEach(s => {
                    this.$set(s, 'canDrag', s.top);
                });
            } else {
                this.multiDrag = false;
                // this.lockArea();
                this.dragLockArea = true;
                this.currentSpuList.forEach(s => {
                    this.$set(s, 'canDrag', !s.top);
                });
            }
        },
        choose (evt) {
            this.computedList(this.lockItemLen - evt.items.length);
            this.currentSpuList[evt.oldIndex].showCount = true;
        },
        // 图片移动
        move (evt, originalEvent) {
            this.cacheLen = this.cacheLen - this.selectItems;
            return !evt.relatedContext.element.canDrag;
        },
        // 图片拖拽结束
        dragend (evt) {
            this.dragLockArea = false;
            this.currentSpuList.forEach(r => {
                r.showCount = false;
            });
            // 确保所有的置顶在前面
            this.imageList.splice(this.pageSize * (this.page - 1), this.pageSize, ...this.currentSpuList);
            const lockItems = this.imageList.filter(res => res.top);
            const unLockGoods = this.imageList.filter(s => !s.top);
            this.lockList = lockItems;
            this.lockItemLen = lockItems.length;
            this.cacheLen = this.lockItemLen;
            this.imageList = [...lockItems, ...unLockGoods];
            this.$emit('input', this.imageList);
            this.$emit('update', {type: 'drag'});
            this.handleCancelSelectAll();
        },
        // 错误图片显示
        fillImg (src) {
            const match = /(http|https):\/\/([\w.]+\/?)\S*/;
            return !match.test(src) ? `https://tlkj-item-pic.oss-cn-beijing.aliyuncs.com${src}` : src;
        },
        updateLocation (item, flag) {
            item.top = flag;
            let tindex = this.imageList.findIndex(res => res.spuId === item.spuId);
            this.imageList.splice(tindex, 1);
            const lockItemIndex = this.imageList.filter(res => res.top).length;
            flag ? this.imageList.unshift(item) : this.imageList.splice(lockItemIndex, 0, item);
            // this.initialCurrentPageSpu();
            this.$emit('input', this.imageList);
            this.$emit('update', {item, type: 'modify', flag});
        },
        actionTop (index, item) { // 置顶
            this.updateLocation(item, true);
        },
        actionCancelTop (index, item) {
            this.updateLocation(item, false);
        },
        actionDelTop (item) {
            let tindex = this.imageList.findIndex(res => res.spuId === item.spuId);
            this.imageList.splice(tindex, 1);
            // this.initialCurrentPageSpu();
            this.$emit('update', {item, type: 'del'});
        },
        initPageItems (page = this.page) {
            const lists = deepClone(this.imageList);
            this.total = lists.length;
            this.pageCount = Math.ceil(this.total / this.pageSize);
            let offset_start = (page - 1) * this.pageSize;
            let offset_end = page * this.pageSize;
            if (offset_end > this.total) {
                offset_end = this.total;
            }
            return lists.slice(offset_start, offset_end);
        },
        initialCurrentPageSpu () {
            // setTimeout(() => {
            const list = this.initPageItems();
            list.forEach((s) => {
                this.$set(s, 'showCount', false);
                this.$set(s, 'canDrag', s.top);
                this.$set(s, 'first', false);
                this.$set(s, 'last', false);
            });
            this.currentSpuList = list;
            this.lockList = list.filter(s => s.top);
            this.lockItemLen = this.lockList.length;
            this.cacheLen = this.lockItemLen;
            // this.lockArea();
            // this.__resizeHandler = debounce(() => {
            //     this.lockArea();
            // }, 200);
            // window.addEventListener('resize', this.__resizeHandler);
            // }, 400);

            // this.$emit('input', this.imageList);
        },
        lockArea () {
            if (this.lockList.length) {
                this.computedList(this.lockItemLen);
            }
        },
        computedList (items) {
            this.cacheLen = items;
            // 获取屏幕宽度
            const devW = document.documentElement.clientWidth - 300;
            // 获取每行最后一个item的下标
            const index = Math.floor(devW / 174); // 170:盒子宽度，1:盒子和盒子间的间隔
            this.everyRowItems = index;
            this.rowItems = Math.ceil(items / index);
            this.ttttt = this.rowItems > 1 && (this.everyRowItems * (this.rowItems - 2) + Math.floor(items % index));
            for (let i = 0; i < this.rowItems; i++) {
                // 循环给最后一个盒子添加样式
                if (i === 0 && this.rowItems > 1) {
                    this.$set(this.lockList[index - 1], 'last', true);
                } else if (this.rowItems > 1) {
                    this.$set(this.lockList[index * i - 1], 'last', true);
                }

                this.$set(this.lockList[index * i], 'first', true);
            }
        },
        handleCurrentChange (val) {
            this.handleCancelSelectAll();
            this.count = 0;
            this.selectNum = 0;
            this.selectItems = [];
            this.page = val;
            this.initialCurrentPageSpu();
        },
        handleSizeChange (val) {
            this.page = 1;
            this.pageSize = val;
            this.initialCurrentPageSpu();
        }
    }
};
</script>

<style scoped lang="scss">
.list-wrap {
  position: relative;

  .drag {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .image-item {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    //overflow: hidden;
    cursor: pointer;
    width: 160px;
    //background-color: #f7f7f7;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;

    .img {
      position: relative;
      overflow: hidden;

      .l-img {
        width: 135px;
        height: 180px;
        object-fit: cover;
      }

      &:hover {
        .label {
          display: flex;
        }
      }

      .right_top_flag {
        position: absolute;
        top: 0;
        right: 0;
        box-shadow: rgb(31 125 248 / 50%) 0px -69.1px 0px 69.1px;
        background-color: rgba(31, 125, 248, 0.5);
        display: flex;
        flex-direction: column;
        align-items: center;
        color: white;
        transform: translateX(30%) rotate(45deg) translateZ(1px);
        width: 88px;
        transform-origin: 40px 16px;
        justify-content: center;

        .top_flag_wrapper > img {
          width: 20px;
        }
      }
    }

    .title {
      margin: 5px 0;
      color: #30344f;
      font-size: 12px;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      white-space: normal;
      text-align: center;
      text-overflow: ellipsis;
      width: 100%;
    }

    .label {
      flex-direction: row;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 32px;
      text-align: center;
      position: absolute;
      bottom: 0;
      background-color: #000000;
      color: white;
      opacity: 0.6;
      display: none;
      line-height: 32px;
    }

    &.seleted-pic {
      border: 1px solid #1f7df8;
      background-color: rgba(31, 125, 248, 0.6);

      .title, .top {
        color: #fff;
      }
    }
  }
}

.collection-product_bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;

  .tag {
    padding: 0 7px;
    font-size: 12px;
    line-height: 20px;
    white-space: nowrap;
    border: 1px solid #d9d9d9;
    color: #999;
  }

  .tag-green {
    color: #4bb081;
    background: #ffffff;
    border: 1px solid #4bb081;
  }

  .top {
    color: rgba(31, 125, 248, 1);
    font-size: 12px;
  }
}

.sortable-ghost {
  background: #a8a8a8;
}

.chosenClass {
  background: #ddd;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.batch-product_item {
  display: flex;
  position: absolute;
  top: -5px;
  left: 0;
  flex-wrap: wrap;
  webkit-transform: translateZ(0);
  -ms-transform: translateZ(0);
  transform: translateZ(0);
  animation-name: fadeIn;
  animation-duration: .2s;

  .mark-item {
    background: rgba(51, 153, 255, 0.2);
    border-bottom: 0;
    border-right: 0;
    border-left: 0;
    position: relative;
    //overflow: hidden;
    cursor: pointer;
    width: 170px;
    height: 276px;
    //background-color: #f7f7f7;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 10px;

   /* &:first-child {
      border-left: 2px dashed #3399ff;
    }

    &:last-child {
      border-right: 2px dashed #3399ff;
    }*/

    &.isFirst {
      border-left: 2px dashed #3399ff;
      border-bottom: 0 !important;
    }

    &.hasTopBorder {
      border-top: 2px dashed #3399ff;
    }

    &.hasRightBorder {
      border-right: 2px dashed #3399ff;
    }

    &.hasBottomBorder {
      border-bottom: 2px dashed #3399ff;
    }

    &.isLast {
      border-bottom: 2px dashed #3399ff !important;
    }
  }
}

.collection_batch_tip {
  padding: 6px 20px;
  background: #dee1e9;
  border-bottom: 1px solid #eaeaea;
  font-size: 12px;
  margin-bottom: 6px;
  position: relative;
  display: flex;
  align-items: center;

  .select_num {
    color: rgba(0, 0, 0, 0.65);

    > span {
      color: #1f7df8;
    }
  }
}
</style>
